//
//  LHRefreshControl.swift
//  sinaWeibo
//
//  Created by LiHong on 15/11/3.
//  Copyright © 2015年 LiHong. All rights reserved.
//

import UIKit

class LHRefreshControl: UIRefreshControl {

    // MARK: - 构造函数
    override init() {
        super.init()
        prepareUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 属性
    /// 判断箭头是否要旋转的值
    private var RefreshControlOffset: CGFloat = -60
    
    // 标记，用于去除重复标记
    private var isUp: Bool = false
    override var frame: CGRect {
        didSet{
            if frame.origin.y >= 0 {
                return
            }
            
            if refreshing {
                refreshView.startLoading()
            }
            
            if frame.origin.y < RefreshControlOffset && !isUp{
                print("箭头转上去")
                isUp = true
                refreshView.rotationTipViewIcon(isUp)
            }else if frame.origin.y > RefreshControlOffset && isUp {
                print("箭头转下去")
                isUp = false
                refreshView.rotationTipViewIcon(isUp)
            }
            
            
        }
    }
    
    
    
    /// 停止刷新
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopLoading()
    }
    
    
    //MARK: - 准备UI
    private func prepareUI(){
        addSubview(refreshView)
        
        //约束
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    }
    
    //MARK: - 懒加载
    private lazy var refreshView: LHRefreshView = LHRefreshView.refreshView()
}

class LHRefreshView: UIView {
    /// 选择图标
    @IBOutlet weak var loadingView: UIImageView!
    /// 箭头
    @IBOutlet weak var tipViewIcon: UIImageView!
    /// 提示加载
    @IBOutlet weak var tipView: UIView!
    
    class func refreshView() -> LHRefreshView {
        return NSBundle.mainBundle().loadNibNamed("LHRefreshView", owner: nil, options: nil).last as! LHRefreshView
    }
    
    /// 箭头选择动画 isUp: true,表示朝上, false,朝下
    func rotationTipViewIcon(isUP: Bool) {
        UIView.animateWithDuration(0.25) { () -> Void in
            self.tipViewIcon.transform = isUP ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01)) : CGAffineTransformIdentity
        }
    }
    /// 开始旋转
    func startLoading() {
        let animKey = "animKey"
        
        if let _ = loadingView.layer.animationForKey(animKey) {
            return
        }
        
        tipView.hidden = true
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = M_PI * 2
        anim.duration = 0.25
        anim.repeatCount = MAXFLOAT
        anim.removedOnCompletion = false

        loadingView.layer.addAnimation(anim, forKey: animKey)
    }
    
    /// 停止旋转
    func stopLoading() {
        tipView.hidden = false
        loadingView.layer.removeAllAnimations()
    }
    
}